package com.iwomy.secureplat.platform.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.iwomy.secureplat.admin.api.entity.SysTenant;
import com.iwomy.secureplat.admin.api.feign.RemoteTenantService;
import com.iwomy.secureplat.common.core.constant.SecurityConstants;
import com.iwomy.secureplat.common.core.util.R;
import com.iwomy.secureplat.common.data.tenant.TenantContextHolder;
import com.iwomy.secureplat.common.security.annotation.Inner;
import com.iwomy.secureplat.platform.constant.NotificationRecordConstants;
import com.iwomy.secureplat.platform.entity.BasicNotificationRecordEntity;
import com.iwomy.secureplat.platform.service.BasicExpensesDviceConfigService;
import com.iwomy.secureplat.platform.service.BasicNotificationRecordService;
import com.iwomy.secureplat.platform.utils.JsonUtil;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 回调接口
 *
 * @author pig
 * @date 2023-08-29 17:58:11
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/callBack")
@Tag(description = "callBack", name = "回调接口")
@Slf4j
public class CallBackController {

	private final BasicNotificationRecordService basicNotificationRecordService;

	private final BasicExpensesDviceConfigService basicExpensesDviceConfigService;


	@RequestMapping("tencentVoice")
	@Inner(value = false)
	public R tencentVoice(@RequestBody String body) {
		//{"voice_failure_callback":{"callid":"e473021c-8ff5-11ee-a181-5254002ab735","failure_code":2,"failure_reason":"正在通话","call_from":"02138344814","mobile":"15259260094","nationcode":"86"}}
//		{"voice_failure_callback":{"callid":"4903de9e-8f6b-11ee-81b8-5254004b70bc","failure_code":28,"failure_reason":"通信助理漏话提醒","call_from":"02138344814","mobile":"18059260094","nationcode":"86"}}
//		{"voiceprompt_callback": {"result": "1","accept_time": "0","call_from": "02138344814","callid": "5b7932d8-8ff5-11ee-a7fc-525400038232","end_calltime": "1701399507","fee": "0","mobile": "15259260094","nationcode": "86","ext": "","start_calltime": "1701399448"}}
		log.info("tencentVoice:{}", body);
		//		0表示用户正常接听
		//		1表示用户未接听
		//		2表示呼叫异常
		//https://cloud.tencent.com/document/product/1128/51533参考文档


		JSONObject jsonObject = JSONObject.parseObject(body);
		String callid = (String) JsonUtil.getValueByKey(jsonObject, "callid").get(0);



		//平台扣钱

		BasicNotificationRecordEntity basicNotificationRecordEntity = basicNotificationRecordService
				.oneBySupplierIdentifying(callid);
		List<Object> resultList = JsonUtil.getValueByKey(jsonObject, "result");
		if(ObjectUtil.isEmpty(resultList)){
			//自接挂断或其他失败原因
			basicNotificationRecordEntity.setCallbackContent(body);
			basicNotificationRecordService.updateById(basicNotificationRecordEntity);
			basicNotificationRecordEntity.setSendResults(NotificationRecordConstants.NOTIFICATION_RECORD_SEND_RESULTS_FAIL);
			return R.failed();
		}
		String result = (String) resultList.get(0);
		basicNotificationRecordEntity.setSendResults("0".equals(result)
				? NotificationRecordConstants.NOTIFICATION_RECORD_SEND_RESULTS_SUCCESS
				: NotificationRecordConstants.NOTIFICATION_RECORD_SEND_RESULTS_FAIL);
		String fee = (String) JsonUtil.getValueByKey(jsonObject, "fee").get(0);

		//平台扣钱
		if ( "0".equals(result)) {
			TenantContextHolder.setTenantId(basicNotificationRecordEntity.getTenantId());
			basicNotificationRecordEntity.setConsumeType(NotificationRecordConstants.NOTIFICATION_RECORD_CONSUME_PLATFORM);
			basicExpensesDviceConfigService
					.deviceDeductTts(basicNotificationRecordEntity.getDeviceId(), Integer.valueOf(fee)
							, basicNotificationRecordEntity.getDeptId(),basicNotificationRecordEntity);
		}


		log.info("通话时间{}分钟", fee);
		//扣除实际时间
		basicNotificationRecordEntity.setCallbackContent(body);
		basicNotificationRecordService.updateById(basicNotificationRecordEntity);
		return R.ok();
	}

	@RequestMapping("tencentSms")
	@Inner(value = false)
	public R tencentSms(@RequestBody String body) {
		//[{"user_receive_time":"2023-12-01 11:01:17","mobile":"15259260094","report_status":"SUCCESS","description":"用户短信送达成功","errmsg":"DELIVRD","nationcode":"86","sid":"4193:21240224017013996672906009"}]
		List<JSONObject> jsonObjects = JSONArray.parseArray(body, JSONObject.class);

		if (ObjectUtil.isEmpty(jsonObjects)) return R.ok();

		for (JSONObject jsonObject : jsonObjects) {
			log.info("tencentSms：{}", jsonObject.toJSONString());
			String sid = jsonObject.getString("sid");
			String reportStatus = jsonObject.getString("report_status");
			BasicNotificationRecordEntity basicNotificationRecordEntity = basicNotificationRecordService.oneBySupplierIdentifying(sid);

			if ("SUCCESS".equals(reportStatus)) {
				TenantContextHolder.setTenantId(basicNotificationRecordEntity.getTenantId());
				basicNotificationRecordEntity.setConsumeType(NotificationRecordConstants.NOTIFICATION_RECORD_CONSUME_PLATFORM);
				basicExpensesDviceConfigService
						.deviceDeductSms(basicNotificationRecordEntity.getDeviceId(), 1
								, basicNotificationRecordEntity.getDeptId(),basicNotificationRecordEntity);
			}
			basicNotificationRecordEntity.setCallbackContent(jsonObject.toJSONString());
			basicNotificationRecordService.updateById(basicNotificationRecordEntity);

		}


		return R.ok();
	}


}